package com.jneagle.xlstool.bzwgjmx.impl.handler;

import com.jneagle.xlstool.bzwgjmx.impl.exception.ParserUnableDetermineException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;

/**
 * 原始数据解析器工厂。
 *
 * @author DwArFeng
 * @since 1.0.0
 */
@Component
public class RawDataRowParserFactory {

    private final ApplicationContext ctx;

    @Value("${raw_data.policy.parser_version.regex}")
    private String parserVersionRegex;
    @Value("${raw_data.policy.parser_version.replacement}")
    private String parserVersionReplacement;

    @Value("${raw_data.parser.v14.keyword}")
    private String v14ParserKeyWord;
    @Value("${raw_data.parser.v15.keyword}")
    private String v15ParserKeyWord;

    public RawDataRowParserFactory(ApplicationContext ctx) {
        this.ctx = ctx;
    }

    RawDataRowParser getParser(File file) throws ParserUnableDetermineException {
        // 获取文件的名称，并使用配置的正则表达式进行替换。
        String fileName = file.getName();
        String parserVersion = fileName.replaceAll(parserVersionRegex, parserVersionReplacement);
        if (Objects.equals(parserVersion, v14ParserKeyWord)) {
            return ctx.getBean(V14RawDataRowParser.class);
        } else if (Objects.equals(parserVersion, v15ParserKeyWord)) {
            return ctx.getBean(V15RawDataRowParser.class);
        } else {
            throw new ParserUnableDetermineException(file);
        }
    }
}
